/*
 * @Author       : NaN 353362604@qq.com
 * @Date         : 2023-05-17 14:34:41
 * @LastEditTime : 2023-07-05 16:36:53
 * @LastEditors  : NaN 353362604@qq.com
 * @FilePath     : \AdminStration\src\Common\Router\MenuNav\module\EditTableModal.jsx
 * @Description  :
 */
import { EditableProTable } from '@ant-design/pro-components'
import { useBoolean, useRequest } from 'ahooks'
import { Button, message, Spin } from 'antd'
import { useState, useEffect } from 'react'
import { v4 as uuidv4 } from 'uuid'
import { Http } from '../../../Api'

export const EditTableModal = ({ height, TableListData, router }) => {
    const [loading, { setTrue, setFalse }] = useBoolean(true)
    const [dataSource, setDataSource] = useState([])
    const [editableKeys, setEditableRowKeys] = useState()
    const [messageApi, contextHolder] = message.useMessage()
    const { runAsync: getData } = useRequest(Http, { manual: true })
    const { runAsync: putData } = useRequest(Http, { manual: true })
    const [TableListParament, setTableListParament] = useState()
    useEffect(() => {
        const { page, ...res } = TableListData
        const getProList = async () => {
            const Template = await import(`../${router}/${page}`).catch(() => false)
            const tableData = await Template[page]({ ...res })
            console.log(tableData)
            getData({ url: tableData.get, path: [tableData.uuid] }).then(res => {
                let list = []
                if (tableData.field && res[tableData.field]) list = JSON.parse(res[tableData.field])
                console.log(tableData)
                setTableListParament(tableData)
                setDataSource(list)
                setEditableRowKeys(list.map(item => item.uuid))
                setFalse()
            })
        }
        if (page) getProList()
    }, [TableListData, getData, height, router, setFalse])

    return (
        <Spin spinning={loading}>
            {TableListParament && (
                <EditableProTable
                    className="EditableProTable"
                    rowKey="uuid"
                    columns={TableListParament.columns}
                    scroll={200}
                    value={dataSource}
                    onChange={setDataSource}
                    recordCreatorProps={{ newRecordType: 'dataSource', record: () => ({ uuid: uuidv4() }) }}
                    toolBarRender={() => {
                        return [
                            <Button
                                type="primary"
                                key="save"
                                onClick={() => {
                                    const { modify, field, addField, uuid, columns } = TableListParament
                                    setTrue()
                                    if (field) {
                                        let params = dataSource.filter(v => v.one)
                                        putData({
                                            url: modify,
                                            data: { [field]: JSON.stringify(params), uuid },
                                            path: [uuid],
                                        }).then(() => {
                                            messageApi.success('数据保存成功')
                                            setFalse()
                                        })
                                    } else {
                                        const data = dataSource.map(e => {
                                            let item = {}
                                            columns.forEach(({ dataIndex }) => {
                                                if (dataIndex)
                                                    item = { ...item, [dataIndex]: e[dataIndex], ...addField }
                                            })
                                            return item
                                        })
                                        putData({ url: modify, data }).then(() => {
                                            messageApi.success('数保存加成功')
                                            setFalse()
                                        })
                                    }
                                }}
                            >
                                保存数据
                            </Button>,
                        ]
                    }}
                    editable={{
                        type: 'multiple',
                        editableKeys,
                        actionRender: (_, __, defaultDoms) => [defaultDoms.delete],
                        onValuesChange: (_, recordList) => setDataSource(recordList),
                        onChange: editableKeys => setEditableRowKeys(editableKeys),
                    }}
                />
            )}

            {contextHolder}
        </Spin>
    )
}
